import React, { Component } from "react";
import { Alert, Steps, Upload, message, Button, Modal, Table } from "antd";
import store from "store";
import "./less/batch.less";
import {
  host,
  systemComDepartImportDepart,
  comInsGetComInsPage, //保全分页
  enterpriseInsComInsGetOnlineInsBlbPreservationLink //生成保全
} from "../../../services/api";

const { Step } = Steps;
let newwin;
// 批量导入-新建组织机构
export default class BatchImport extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      addpeoplevisible: false,
      addpeoplevisible1: false,
      dataSource: [],
      perIds: [],
      //导入人员
      visible: false,
      visibleFormat: false,
      uploadResponse: [], //格式正确后返回的json字符串
      dataFormat: "" //格式错误提示内容
    };
  }
  componentWillMount() {
    this.comInsGetComInsPage();
  }

  //批量导入组织架构
  systemComDepartImportDepart = () => {
    systemComDepartImportDepart({
      data: JSON.stringify(this.state.uploadResponse)
    }).then(
      data => {
        if (data.msg !== "") {
          data.msg = data.msg.replace(/<br>/, "").trim();
        }
        message.success(data.msg);
        console.log(
          data,
          "systemComDepartImportDepart-response-批量导入组织架构"
        );
        const perIds = data.data.map(val => val.perId);
        this.setState({ perIds });
        if (this.state.dataSource.length > 0) {
          this.setState({
            addpeoplevisible: true
          });
        }
      },
      err => {
        console.log(err, "systemComDepartImportDepart-err-批量导入组织架构");
      }
    );
  };

  showModal = () => {
    this.setState({
      visible: true
    });
  };

  handleOk = ifError => {
    this.setState({
      visible: false
    });
    if (!ifError) {
      this.systemComDepartImportDepart();
    }
  };

  handleCancel = e => {
    console.log(e);
    this.setState({
      visible: false
    });
  };
  comInsGetComInsPage = () => {
    comInsGetComInsPage({
      pageSize: 5000,
      pageNumber: 1,
      buyMode: "1"
    })
      .then(res => {
        console.log(res, "保险分页-res");
        const dataSource = res.data.data.map(val => {
          val.key = val.blbOrderId;
          return val;
        });
        this.setState({ dataSource });
      })
      .catch(err => console.log(err));
  };

  //保险选择
  renderTable = () => {
    const rowSelection = {
      type: "radio",
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: selectedRowKeys => {
        this.setState({ selectedRowKeys });
      },
      getCheckboxProps: record => ({
        disabled: record.name === "Disabled User" // Column configuration not to be checked
      })
    };
    const columns = [
      {
        title: "订单号",
        dataIndex: "blbOrderId",
        key: "blbOrderId"
      },
      {
        title: "保险产品",
        dataIndex: "insComName",
        key: "insComName"
      },
      {
        title: "人数",
        dataIndex: "perNum",
        key: "perNum"
      },
      {
        title: "购买时间",
        dataIndex: "effectStartDate",
        key: "effectStartDate"
      }
    ];

    return (
      <Table
        size="middle"
        width={800}
        rowSelection={rowSelection}
        columns={columns}
        pagination={false}
        dataSource={this.state.dataSource}
      />
    );
  };

  //保全链接生成
  enterpriseInsComInsGetOnlineInsBlbPreservationLink = () => {
    enterpriseInsComInsGetOnlineInsBlbPreservationLink({
      orderId: this.state.selectedRowKeys,
      perIds: this.state.perIds.join(","),
      reviseType: "1"
    })
      .then(res => {
        console.log(res, "保全链接生成-res");
        this.setState({ addpeoplevisible1: false });
        newwin.location.href = res.data;
      })
      .catch(err => {
        newwin.close();
        this.setState({ addpeoplevisible1: false });
        console.log(err, "保全链接生成-err");
      });
  };

  //格式错误提示框
  handleFormatOk = () => {
    this.setState({ visibleFormat: false });
  };

  //下载
  handleClickLink = () => {
    return (
      <Button
        type="primary"
        onClick={() =>
          window.open(`${host}/system/com-depart/export-depart-temp`, "_self")
        }
      >
        下载模板
      </Button>
      // <Button type="primary" onClick={() => window.open(`${lib.host}/static/template/OrderPerson_Template.xls`, "_self")}>下载模板</Button>
    );
  };
  //上传
  handleClickUpload = () => {
    const uploadExcel = {
      name: "xfile",
      action: `${host}/system/com-depart/get-import-depart-json`,
      headers: {
        authorization: "Basic c2Fhc3dlYjp3ZWI=",
        access_token: store.get("saas")["access_token"]
      },
      showUploadList: false,
      data: {}
    };
    const beforeUpload = file => {
      let ifError = true;
      console.log(file);
      if (file.name.indexOf("xls") === -1 && file.name.indexOf("xlsx") === -1) {
        message.error("请上传xls或xlsx文件!");
        ifError = false;
      }
      return ifError;
    };

    //上传文件
    const UploadChange = info => {
      if (info.file.status === "uploading") {
        return;
      }
      console.log(info.file.name);
      if (info.file.status === "done") {
        console.log(info.file.response.data);
        const { data, msg } = info.file.response;
        //判断格式是否正确
        //如果没有返回data，则提示msg内容
        //如果data没有数组，则是格式错误，否则为其他错误提示
        console.error(info.file.response);
        if (!data) {
          this.setState({ visibleFormat: true, dataFormat: msg });
        } else {
          this.setState(
            {
              uploadResponse: info.file.response.data.map((val, key) => ({
                ...val,
                ...{ key }
              }))
            },
            () => {
              this.setState({ visible: true });
            }
          );
        }
        if (info.file.response.retType === 0) {
          // message.success(info.file.response.msg);
        }
      }
    };
    return (
      <Upload
        onChange={UploadChange}
        beforeUpload={beforeUpload}
        {...uploadExcel}
      >
        <Button type="primary">选择上传文件</Button>
      </Upload>
    );
  };

  //导入通讯录
  renderUploadResult = () => {
    const columns = [
      {
        title: "姓名",
        dataIndex: "name",
        key: "name",
        // fixed: 'left',
        width: "120"
      },
      {
        title: "证件类型",
        dataIndex: "idCardType",
        key: "idCardType"
      },
      {
        title: "证件号码",
        dataIndex: "idCardNo",
        key: "idCardNo"
      },
      {
        title: "手机号",
        dataIndex: "mobilePhone",
        key: "mobilePhone"
      },
      {
        title: "部门名称",
        dataIndex: "departName",
        key: "departName",
        width: "140px"
      },
      {
        title: "角色",
        dataIndex: "roleName",
        key: "roleName",
        width: "130px"
      },
      {
        title: "入职时间",
        dataIndex: "entryDate",
        key: "entryDate"
      },
      {
        title: "校验提示",
        dataIndex: "errorMsg",
        key: "errorMsg"
      }
    ];

    //格式错误列展示
    let uploadResponse = JSON.parse(JSON.stringify(this.state.uploadResponse));
    //后台的为null 统一转""
    uploadResponse = uploadResponse.map(val => {
      Object.keys(val).forEach(v => {
        if (v === "entryDate") {
          val[v] = val[v].slice(0, 10);
        }
        if (!val[v]) {
          val[v] = "";
        }
      });
      return val;
    });
    console.log(uploadResponse);
    //过滤，包含错误信息的数组
    const errorLength = uploadResponse.filter(
      val => val.errorMsg.trim() !== ""
    );
    const ifError = errorLength.length !== 0; //判断是否包含错误信息
    let alert = "";
    if (ifError) {
      //上传失败
      uploadResponse = uploadResponse.map(val => {
        if (val.errorMsg !== "") {
          val.errorMsg = val.errorMsg.replace(/<br>/, "").trim();
        }
        return val;
      });
      alert = (
        <Alert
          message={`本次上传失败，共 ${
            uploadResponse.length
          } 条员工数据，其中有 ${
            errorLength.length
          } 条员工的信息格式校验有误。请核对，若有误，则调整 excel`}
          type="error"
          showIcon
        />
      );
    } else {
      //上传成功
      alert = (
        <Alert
          message={`本次上传全部成功，共上传${
            uploadResponse.length
          }条员工数据。请再次核对，无误则确认导入~`}
          type="success"
          showIcon
        />
      );
      columns.pop();
      console.log("columns");
    }
    console.log(ifError);
    console.log(uploadResponse);

    return (
      <Modal
        title="导入通讯录"
        visible={this.state.visible}
        onOk={this.handleOk.bind(this, ifError)}
        okText={`${ifError ? "有误，稍后上传" : "确认无误"}`}
        onCancel={this.handleCancel}
        cancelText="取消"
        width="1200px"
      >
        {alert}
        <Table
          columns={columns}
          dataSource={uploadResponse}
          pagination={pageInitStudent}
          style={{ marginTop: "16px" }}
        />
      </Modal>
    );
  };

  //加载格式错误提示框
  renderUploadFormat = () => {
    const columnsFormat = [
      {
        title: "序号",
        dataIndex: "index",
        key: "index"
      },
      {
        title: "错误提示",
        dataIndex: "info",
        key: "info"
      }
    ];
    const { dataFormat } = this.state;
    const [total, ...errorInfo] = dataFormat.split("<br>");
    if (errorInfo.length !== 1) {
      errorInfo.pop();
    }
    const errorInfos = errorInfo.map((val, key) => {
      return {
        index: key + 1,
        info: val,
        key
      };
    });
    return (
      <Modal
        title="导入通讯录"
        visible={this.state.visibleFormat}
        onOk={this.handleFormatOk}
        okText="有误，稍后上传"
        onCancel={this.handleFormatOk}
        cancelText=""
      >
        <Alert
          message={`本次上传失败，共 ${total} 条员工数据，其中有 ${
            errorInfos.length
          } 条员工的信息格式校验有误。请核对，若有误，则调整 excel`}
          type="error"
          showIcon
        />
        <Table
          columns={columnsFormat}
          dataSource={errorInfos}
          pagination={pageInitStudent}
          style={{ marginTop: "16px" }}
        />
      </Modal>
    );
  };

  render() {
    return (
      <div className="BatchImport">
        <div className="batch-content">
          <div className="batch-body">
            <div className="tabs-content">
              <Steps direction="vertical" size="small" current={1}>
                <Step
                  title="下载员工信息模板，批量填写员工信息"
                  description={this.handleClickLink()}
                />
                <Step
                  title="上传填写好的员工信息表"
                  description={this.handleClickUpload()}
                />
              </Steps>
            </div>
            <div className="upload">
              {/* <Button size="large" type="primary" onClick={this.showModal}>
                确认上传
              </Button> */}
              {/* 导入通讯录弹窗 */}
              {this.renderUploadResult()}

              {/*格式错误提示框*/}
              {this.renderUploadFormat()}
            </div>
          </div>
        </div>
        <Modal
          className="reducepeople"
          title="保险员增员提示"
          visible={this.state.addpeoplevisible}
          onOk={this.handlereducepeopleOk}
          onCancel={() => this.setState({ addpeoplevisible: false })}
          footer={[
            <Button
              key="cancel"
              onClick={() => this.setState({ addpeoplevisible: false })}
            >
              取消
            </Button>,
            <Button
              key="submit"
              type="primary"
              onClick={() => {
                this.setState({
                  addpeoplevisible: false,
                  addpeoplevisible1: true
                });
              }}
            >
              马上办理
            </Button>
          ]}
        >
          <div>
            <div>
              <Alert
                message="保险产品的增员、减员、替换等操作可通过【金融保险】-【保险订单】-选择有效订单的【保全】对保单中的人员增减操作！"
                type="warning"
                showIcon
              />
            </div>
            <p>
              本次新增人员共{this.state.perIds.length}
              位，企业目前已购买团意险产品[产品名称]（订单号：[订单编号]），企业可对新增人员办理保险保全的增员操作。
            </p>
          </div>
        </Modal>

        <Modal
          width={1000}
          title="选择订单"
          visible={this.state.addpeoplevisible1}
          onCancel={() => this.setState({ addpeoplevisible1: false })}
          footer={[
            <Button
              key="submit1"
              onClick={() => {
                this.setState({ addpeoplevisible1: false });
              }}
            >
              取消
            </Button>,
            <Button
              key="submit"
              type="primary"
              onClick={() => {
                if (!this.state.selectedRowKeys) {
                  message.error("请选择订单");
                  return null;
                }
                newwin = window.open("about:blank");
                this.enterpriseInsComInsGetOnlineInsBlbPreservationLink();
              }}
            >
              确认
            </Button>
          ]}
        >
          {this.renderTable()}
        </Modal>
      </div>
    );
  }
}

const pageInitStudent = {
  defaultPageSize: 10,
  showQuickJumper: true,
  pageSizeOptions: ["10", "20", "50"],
  showSizeChanger: true
};
